package com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import com.yuexunit.operationman.nbsy.R;
import com.yuexunit.operationman.nbsy.base.BaseKJActivity;
import com.yuexunit.operationman.nbsy.base.ExitApplication;
import com.yuexunit.operationman.nbsy.base.SubmitBean;
import com.yuexunit.operationman.nbsy.config.AppConfig;
import com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.bean.RiskAssessmentBean;
import com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.model.impl.RiskAssessmentModel;
import com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.presenter.IRiskAssessmentPresenter;
import com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.presenter.impl.RiskAssessmentPresenter;
import com.yuexunit.operationman.nbsy.module.OperationRiskAssessment.ui.view.IRiskAssessmentView;
import com.yuexunit.operationman.nbsy.widget.CustomDatePicker;
import com.yuexunit.operationman.nbsy.widget.LoadingDialog;

import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2017/8/9 0009.
 */

public class Act_RiskAssessmentEvaluate extends BaseKJActivity implements IRiskAssessmentView {

    @Bind(R.id.tv_patient_name)
    TextView tvPatientName;
    @Bind(R.id.tv_patient_sex)
    TextView tvPatientSex;
    @Bind(R.id.tv_patient_visitno)
    TextView tvPatientVisitno;
    @Bind(R.id.tv_patient_disease)
    TextView tvPatientDisease;
    @Bind(R.id.evalu_01)
    TextView evalu01;
    @Bind(R.id.evalu_02)
    TextView evalu02;
    @Bind(R.id.evalu_03)
    TextView evalu03;
    @Bind(R.id.evalu_04)
    TextView evalu04;
    @Bind(R.id.num)
    TextView num;
    @Bind(R.id.doc_name)
    EditText docName;
    @Bind(R.id.select_time)
    TextView selectTime;
    @Bind(R.id.iv_select_time)
    LinearLayout ivSelectTime;

    int scale = 0;

    LoadingDialog loadingDialog;
    IRiskAssessmentPresenter presenter;


    @Override
    public void setRootView() {
        setContentView(R.layout.act_riskassessmentevaluate);
        ButterKnife.bind(this);
        ExitApplication.getInstance().addActivity(this);
    }

    @Override
    public void initData() {
        super.initData();
        loadingDialog = new LoadingDialog(this);
        presenter = new RiskAssessmentPresenter(this, new RiskAssessmentModel());
        setTitle();
        setContent();
    }

    private void setTitle() {
        tvPatientName.setText(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getPatientName());
        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getPatientSex().equals("1")) {
            tvPatientSex.setText("男");
        } else if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getPatientSex().equals("2")) {
            tvPatientSex.setText("女");
        } else {
            tvPatientSex.setText("不详");
        }
        tvPatientVisitno.setText("住院号" + AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getInHospitalNo());
        tvPatientDisease.setText(PreferenceHelper.readString(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_DISEASE));
    }

    private void setContent() {
        for (RiskAssessmentBean.ObjectEntity.RiskItemListEntity p : AppConfig.RISKASSESSMENTBEAN.getObject().getRiskItemList()) {
            switch (p.getItemCode()) {
                case "QK_L":
                    if (p.getItemValue().length() > 0) {
                        String[] skin = p.getItemValue().split(";", -1);
                        evalu01.setText(skin[1] + "分");
                    }
                    break;
                case "MZ_P":
                    if (p.getItemValue().length() > 0) {
                        String[] skin = p.getItemValue().split(";", -1);
                        evalu02.setText(skin[1] + "分");
                    }
                    break;
                case "SJ_T":
                    if (p.getItemValue().length() > 0) {
                        String[] skin = p.getItemValue().split(";", -1);
                        evalu03.setText(skin[1] + "分");
                    }
                    break;
            }
        }

        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskScore() != null) {
            evalu04.setText(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskScore() + "分");
        }

        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskRank() != null) {
            num.setText(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskRank());
        }

        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskDoctor() != null) {
            docName.setText(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskDoctor());
        }

        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskDate() != null) {
            ivSelectTime.setEnabled(false);
            selectTime.setText(AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskDate());
        }
    }

    @OnClick({R.id.titlebar_docadvice_img_back, R.id.subtract, R.id.add, R.id.iv_select_time, R.id.sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titlebar_docadvice_img_back:
                finish();
                break;
            case R.id.subtract:
                if (scale > 0) {
                    scale--;
                } else {
                    scale = 10;
                }
                num.setText(scale + "");
                break;
            case R.id.add:
                if (scale < 10) {
                    scale++;
                } else {
                    scale = 0;
                }
                num.setText(scale + "");
                break;
            case R.id.iv_select_time:
                initDatePicker(selectTime);
                break;
            case R.id.sure:
                insertContent();
                break;
        }
    }

    private void insertContent() {
        if (num.getText().toString().length() > 0) {
            AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().setRiskRank(num.getText().toString());
        }
        if (docName.getText().toString().length() > 0) {
            AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().setRiskDoctor(docName.getText().toString());
        }
        if (selectTime.getText().toString().length() > 0) {
            AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().setRiskDate(selectTime.getText().toString());
        }

        if (AppConfig.RISKASSESSMENTBEAN.getObject().getRisk().getRiskId() == null) {
            Map<String, String> params = new HashMap<>();
            params.put("operationNo", PreferenceHelper.readString(aty, AppConfig.PATIENT_INFO, AppConfig.PATIENT_OPERATION_ID) + "");
            params.put("saveData", JSON.toJSONString(AppConfig.RISKASSESSMENTBEAN));
            presenter.insertRiskAssessmentDate(params);
        } else {
            Map<String, String> params = new HashMap<>();
            params.put("accountId", PreferenceHelper.readInt(aty, AppConfig.USER_INFO, AppConfig.USER_ACCOUNT) + "");
            params.put("fullName", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.USER_FULLNAME) + "");
            params.put("saveData", JSON.toJSONString(AppConfig.RISKASSESSMENTBEAN));
            presenter.updateRiskAssessmentDate(params);
        }
    }

    private void initDatePicker(final TextView view) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        Date date1 = null;
        try {
            if (view.getText().toString().length() > 0) {
                date1 = sdf.parse(view.getText().toString());
            } else {
                date1 = new Date();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String now = sdf.format(date1);

        CustomDatePicker customDatePicker1 = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                view.setText(time);
            }
        }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker1.showSpecificTime(true); // 显示时和分
        customDatePicker1.setIsLoop(true); // 循环滚动
        customDatePicker1.show(now);
    }

    @Override
    public void insertRiskAssessmentDate(SubmitBean submitBean) {
        if (submitBean.getCode() == 200) {
            ViewInject.toast("保存成功");
            finish();
        } else {
            ViewInject.toast(submitBean.getDesc());
        }
    }

    @Override
    public void updateRiskAssessmentDate(SubmitBean submitBean) {
        if (submitBean.getCode() == 200) {
            ViewInject.toast("保存成功");
            finish();
        } else {
            ViewInject.toast(submitBean.getDesc());
        }
    }

    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                loadingDialog.setCanceledOnTouchOutside(false);
                loadingDialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                loadingDialog.dismiss();
                break;

        }
    }

    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
